今天就來說說 expect() 與 expect {} 的差別吧
我們用一個例子來講
describe 'Post #create' do
let(:params_collection) { { collection: { title: '11', description: '222' } } }
let(:create_collection) { post '/collections', params: params_collection }
it 'redirect to index when create collection success' do
create_collection
expect(Collection.count).to eq 1
end
end
當我們打 post create 時會新建出一個 collection 且會期望會使 Collection 的數量增加 1
如果改成 block 的寫法就會像是
it 'redirect to index when create collection success' do
expect{ create_collection }.to change { Collection.count }.by(1)
end
其實就是在告訴 expect 欸你 block 裡面的create_collection做完之後幫我看一下我 collection 的數量有沒有加 1
describe 'Get #show' do
let(:collection) { create(:collection) }
it 'redirect to index when create collection success' do
expect { get "/collections/1" }.to raise_error(ActiveRecord::RecordNotFound)
end
也可以用{} 去觀察當我打了get "/collections/1" 的時候應該要起error而且是ActiveRecord::RecordNotFound因為我連實體都還沒建立出來,怎麼可能會找得到collection
那我們就會知道
expect() => 當你只想驗證回傳一個值的時候就用 ()expect{} => 當你期望 block 做事情的這段內會發生哪些變化時就該使用 {}